/**
 * @author Ivan Holub
 */
class ArtistController {
    
    def index = { redirect(action:list,params:params) }

    def list = {
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  10)
        if (!params.sort) {
            params.sort = "name"
        }
        [ artistInstanceList: Artist.list( params ), artistInstanceTotal: Artist.count() ]
    }

    def show = {
        def artistInstance = Artist.get( params.id )
        if(!artistInstance) {
            flash.message = "Artist not found with id ${params.id}"
            redirect(action:list)
        }
        else { return [ artistInstance : artistInstance ] }
    }

    def delete = {
        def artistInstance = Artist.get( params.id )
        artistInstance.delete()
        flash.message = "Artist ${artistInstance.name} deleted"
        redirect(action:list)
    }

    def edit = {
        def artistInstance = Artist.get( params.id )
        return [ artistInstance : artistInstance ]
    }

    def update = {
        def artistInstance = Artist.get( params.id )
        def artistNameOld = artistInstance.name
        def isSuccess = false
        if (artistNameOld == params.name) {
            isSuccess = true
        }
        if (!isSuccess) {
            def artistOther = Artist.findByName(params.name);
            if (artistOther == null) {
                isSuccess = true
            }
        }
        if (!isSuccess) {
            def artistInstanceNew = new Artist()
            artistInstanceNew.properties = params
            artistInstanceNew.id = artistInstance.id
            artistInstanceNew.errors.rejectValue("name", "", "Artist with such name already exists.")
            render(view:'edit',model:[artistInstance:artistInstanceNew])
        }
        else {
            artistInstance.properties = params
            if(!artistInstance.hasErrors() && artistInstance.save()) {
                flash.message = "Artist ${params.id} updated"
                redirect(action:show,id:artistInstance.id)
            }
            else {
                render(view:'edit',model:[artistInstance:artistInstance])
            }
        }
    }

    def create = {
        def artistInstance = new Artist()
        artistInstance.properties = params
        return ['artistInstance':artistInstance]
    }

    def save = {
        def isSuccess = false
        def artistOther = Artist.findByName(params.name);
        if (artistOther == null) {
            isSuccess = true
        }
        def artistInstance = new Artist(params)
        if (!isSuccess) {
            artistInstance.errors.rejectValue("name", "", "Artist with such name already exists.")
        }
        if(!artistInstance.hasErrors() && artistInstance.save()) {
            flash.message = "Artist ${artistInstance.id} created"
            redirect(action:show,id:artistInstance.id)
        }
        else {
            render(view:'create',model:[artistInstance:artistInstance])
        }
    }
}
